package com.example.hybridmobiledemo.module.main.model.news.search;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hybridmobiledemo.R;
import com.example.hybridmobiledemo.bean.SHSQLInfo;
import com.example.hybridmobiledemo.databinding.ActivitySearchBinding;
import com.example.hybridmobiledemo.module.main.bean.NewsInfo;
import com.example.hybridmobiledemo.module.main.bean.SCNewsAllInfo;
import com.example.hybridmobiledemo.util.MyDataAdapter;
import com.example.hybridmobiledemo.util.OkHttpUtils;
import com.example.hybridmobiledemo.util.SearHistorySQLiteOpenHelper;
import com.example.hybridmobiledemo.view.FlowLayout;
import com.example.hybridmobiledemo.view.NewsRvAdapter;
import com.example.hybridmobiledemo.view.SeaPRvAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity {
    private ActivitySearchBinding binding;
    private EditText editSearch;
    private TextView tvSearCancel, tvSearChPutTitle, tvSearchEmpty;
    private ImageView imgFlowDelete;
    private FlowLayout flowSearchHis;
    private RecyclerView rvSearchPut;
    private LayoutInflater mInflater;
    private ArrayList<String> mVals=new ArrayList<String>(){};
    private List<SHSQLInfo> sqlList = new ArrayList<SHSQLInfo>();
    private List<NewsInfo> newsInfoList = new ArrayList<NewsInfo>();
    private SearHistorySQLiteOpenHelper openHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = ActivitySearchBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();
        initFlowData();
        initData();
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.builder()
                        .url("interface/SCNews/getAll")
                        .addParam("userId", "ODky")
                        .get()
                        .async(new OkHttpUtils.AsyncCallBack() {
                            @Override
                            public void onResponse(String json) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Gson gson = new Gson();
                                        SCNewsAllInfo info = gson.fromJson(json, SCNewsAllInfo.class);
                                        List<SCNewsAllInfo.DataBean> list = info.getData();
                                        int rollImg = (int) (Math.random() * list.size());
                                        while (rollImg > list.size() - 3) {
                                            rollImg = (int) (Math.random() * list.size());
                                        }
                                        for (int i = rollImg; i < rollImg+3; i++) {
                                            String scNewsTypeId = String.valueOf(list.get(i).getsCNewsTypeId());
                                                int newsId = list.get(i).getId();
                                                String name = list.get(i).getName();
                                                String content = list.get(i).getContent();
                                                int createTime = list.get(i).getCreateTime();
                                                String author = list.get(i).getAuthor();
                                                newsInfoList.add(new NewsInfo(newsId, scNewsTypeId,
                                                        name, content, createTime, author));
                                        }
                                        rvSearchPut.setLayoutManager(new LinearLayoutManager(SearchActivity.this));
                                        rvSearchPut.setAdapter(new SeaPRvAdapter(newsInfoList, SearchActivity.this));
                                    }
                                });
                            }

                            @Override
                            public void onFailure(Exception e) {

                            }
                        });
            }
        }).start();
    }

    private void initFlowData() {
        try {
            sqlList = new MyDataAdapter().QueryAll(SearchActivity.this);
        } catch (Exception e) {
            Log.i("TAG", "SQL NULL");
        }
        for (SHSQLInfo s : sqlList) {
            mVals.add(s.getContent());
        }
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 5, 10, 5);
        if (flowSearchHis != null) {
            flowSearchHis.removeAllViews();
        }
        for (int i = 0; i <mVals.size() ; i++) {
            TextView tv = new TextView(this);
            tv.setPadding(28, 10, 28, 10);
            tv.setText(mVals.get(i));
            tv.setMaxEms(10);
            tv.setSingleLine();
            tv.setBackgroundResource(R.drawable.textview_bg);
            tv.setLayoutParams(layoutParams);
            flowSearchHis.addView(tv, layoutParams);
        }
    }

    private void initView() {
        tvSearChPutTitle = binding.tvSearChPutTitle;
        tvSearchEmpty = binding.tvSearchEmpty;
        editSearch = binding.editSearch;
        tvSearCancel = binding.tvSearCancel;
        imgFlowDelete = binding.imgFlowDelete;
        flowSearchHis = binding.flowSearchHis;
        rvSearchPut = binding.rvSearchPut;
        mInflater = LayoutInflater.from(this);

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    String search = editSearch.getText().toString().trim();
                    if (search.equals("")) {
                        Toast.makeText(SearchActivity.this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                    } else  {
                        tvSearChPutTitle.setText("搜索结果");
                        new MyDataAdapter().insert(SearchActivity.this, new SHSQLInfo(search));
                        mVals.clear();
                        initFlowData();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                OkHttpUtils.builder()
                                        .url("interface/SCNews/search")
                                        .addParam("userId", "ODky")
                                        .addParam("name", search)
                                        .get()
                                        .async(new OkHttpUtils.AsyncCallBack() {
                                            @Override
                                            public void onResponse(String json) {
                                                try {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            Gson gson = new Gson();
                                                            SCNewsAllInfo info = gson.fromJson(json, SCNewsAllInfo.class);
                                                            List<SCNewsAllInfo.DataBean> list = info.getData();
                                                            newsInfoList.clear();
                                                            if (list.size() != 0) {
                                                                for (int i = 0; i < list.size(); i++) {
                                                                    String scNewsTypeId = String.valueOf(list.get(i).getsCNewsTypeId());
                                                                    int newsId = list.get(i).getId();
                                                                    String name = list.get(i).getName();
                                                                    String content = list.get(i).getContent();
                                                                    int createTime = list.get(i).getCreateTime();
                                                                    String author = list.get(i).getAuthor();
                                                                    newsInfoList.add(new NewsInfo(newsId, scNewsTypeId,
                                                                            name, content, createTime, author));
                                                                }
                                                            }
                                                            if (newsInfoList.size() == 0) {
                                                                tvSearchEmpty.setVisibility(View.VISIBLE);
                                                            } else {
                                                                tvSearchEmpty.setVisibility(View.GONE);
                                                            }
                                                            rvSearchPut.setLayoutManager(new LinearLayoutManager(SearchActivity.this));
                                                            rvSearchPut.setAdapter(new NewsRvAdapter(newsInfoList, SearchActivity.this));
                                                        }
                                                    });
                                                } catch (Exception e) {
                                                    Log.e("TAG", "runOnUiThread");
                                                }
                                            }

                                            @Override
                                            public void onFailure(Exception e) {

                                            }
                                        });
                            }
                        }).start();
                    }

                    return true;
                }
                return false;
            }
        });
        
        tvSearCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        
        imgFlowDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MyDataAdapter().deleteAll(SearchActivity.this);
                mVals.clear();
                initFlowData();
            }
        });
    }
}